package com.ms.framework.db.support;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ms.framework.Annotation.Convert;
import com.ms.framework.Constans.MethodPrefix;
import com.ms.framework.db.FieldConvert;
import com.ms.framework.util.StringUtil;

/**   
 * @see
 * @author jingyul
 * @version 1.0
 * @preserve protected
 */
public class EntityDBValueParse implements IDBValueParse {
	private   static   Log   log   =   LogFactory.getLog(EntityDBValueParse.class); 
	protected HashMap<String,Method> methods = new HashMap();
	public Object getValue(Object o,String column,Connection conn)throws Exception {
		Method   m  = this.getMethodName(o, column, MethodPrefix.get);
		try {
			Object val = m.invoke(o, null);
			Convert convert = m.getAnnotation(Convert.class);
			
			if(convert!=null){
				FieldConvert fieldConvert = convert.type().newInstance();
				return fieldConvert.toDbField(val, conn);
			}
			return val;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("Entity column Parse error "+column +" from "+o +e.getMessage());
			throw e;
		}
	}
	public Object[] getValue(Object o,Object[] columns,Connection conn)throws Exception {
		Object[] values = new Object[columns.length];
		for(int i=0;i<columns.length;i++){
			String str =(String)columns[i];
			values[i] = this.getValue(o,str,conn);
		}
		return values;
	}
	public Object[] getValue(Object o,List<String> columns,Connection conn)throws Exception {
		Object[] values = new Object[columns.size()];
		for(int i=0;i<columns.size();i++){
			String str = columns.get(i);
			values[i] = this.getValue(o,str,conn);
		}
		return values;
	}
	private Method getMethodName(Object o,String column,MethodPrefix p){
		synchronized(methods){
			Method  m = this.methods.get(p.toString()+column);
			
			
			if(m!=null){
				return m;
			}
			String methodName = StringUtil.converMethodName(column,p.toString(), "");
			
			try{
				m = o.getClass().getMethod(methodName, null);
				this.methods.put(column, m);
				return m;
			}catch(NoSuchMethodException e){
				log.error("not find "+methodName +"from "+o +e.getMessage());
			}
		}
		return null;
	}
	
}
